package com.xuan.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.reflection.MetaObject;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.lang.reflect.Field;
import java.time.LocalDateTime;

@Configuration
@MapperScan("com.xuan.mapper")
public class MybatisPlusConfig {
    @Bean
    //Bean类似Bean标签
    // 拦截器配置，用来分页
    public MybatisPlusInterceptor plusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        return mybatisPlusInterceptor;
    }

    // 1. 插入时自动填充字段
    @Override
    public void insertFill(MetaObject metaObject) {
        // 设置创建时间为当前时间
        setCurrentTimeForField("createTime", metaObject);
        // 设置更新时间为当前时间
        setCurrentTimeForField("updateTime", metaObject);
    }


    @Override
    public void updateFill(MetaObject metaObject) {
        // 仅设置更新时间为当前时间
        setCurrentTimeForField("updateTime", metaObject);
    }

    // 辅助方法：为指定字段设置当前时间
    private void setCurrentTimeForField(String fieldName, MetaObject metaObject) {
        this.setFieldValByName(fieldName, LocalDateTime.now(), metaObject);
    }

    private void setFieldValByName(String fieldName, LocalDateTime now, MetaObject metaObject) {
        // 获取目标对象
        Object targetObject = metaObject.getOriginalObject();

        // 遍历目标对象的类及其父类的所有字段
        for (Class<?> currentClass = targetObject.getClass(); currentClass != Object.class; currentClass = currentClass.getSuperclass()) {
            try {
                // 获取指定名称的字段
                Field field = currentClass.getDeclaredField(fieldName);
                field.setAccessible(true);
                field.set(targetObject, now);
                break;
            } catch (NoSuchFieldException e) {
                // 如果当前类没有这个字段，尝试父类
                continue;
            } catch (IllegalAccessException e) {
                // 如果字段不可访问，抛出异常
                throw new RuntimeException("无法访问字段：" + fieldName, e);
            }
        }
    }
}
